package com.itany.corejava.code13_jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author MissChen
 * @version 1.0
 * @date 2023 年12月11日 16:36
 */
public class Test04_基本操作 {
    public static void main(String[] args) {
        User user = new User("黄晓明", "123456", "15852365412", "江苏-扬州");
        User user2 = new User(4, "黄baby", "12345678", "15852365411", "山东-青岛");
        try {
            // insertUser(user);
            // deleteById(3);
            // updateUser(user2);
            User user3=findUserById(4);
            System.out.println(user3);
        } catch (DataAccessException e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * 添加用户
     *
     * @param user
     * @throws DataAccessException
     */
    public static void insertUser(User user) throws DataAccessException {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = JDBCUtil.getConnection();

            // 实际开发中，很多sql可能比较长，此时可以使用StringBuffer进行sql的拼接
            String sql = new StringBuffer()
                    .append("insert into ")
                    .append(" t_user ")
                    .append(" (username,password,phone,address) ")
                    .append(" values ")
                    .append(" (?,?,?,?) ")
                    .toString();

            ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getPhone());
            ps.setString(4, user.getAddress());

            //执行DML操作
            int row = ps.executeUpdate();
            System.out.println("数据库中" + row + " rows affected");

        } catch (DataAccessException e) {
            throw e;
        } catch (SQLException e) {
            throw new DataAccessException("数据库访问异常");
        } finally {
            JDBCUtil.close(conn, ps, null);
        }
    }

    /**
     * 根据id删除用户
     *
     * @param id
     */
    public static void deleteById(Integer id) throws DataAccessException {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" delete from t_user ")
                    .append(" where id=? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1, id);
            int row = ps.executeUpdate();
            System.out.println("数据库中" + row + " rows affected");
        } catch (DataAccessException e) {
            throw e;
        } catch (SQLException e) {
            throw new DataAccessException("数据库访问异常");
        } finally {
            JDBCUtil.close(conn, ps, null);
        }

    }

    /**
     * 修改用户
     *
     * @param user
     * @throws DataAccessException
     */
    public static void updateUser(User user) throws DataAccessException {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" update t_user ")
                    .append(" set username=?, ")
                    .append(" password=?, ")
                    .append(" phone=?, ")
                    .append(" address=? ")
                    .append(" where id=? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getPhone());
            ps.setString(4, user.getAddress());
            ps.setInt(5, user.getId());
            int row = ps.executeUpdate();
            System.out.println("数据库中" + row + " rows affected");
        } catch (DataAccessException e) {
            throw e;
        } catch (SQLException e) {
            throw new DataAccessException("数据库访问失败");
        } finally {
            JDBCUtil.close(conn, ps, null);
        }
    }


    /**
     * 根据id查找对应的用户
     *
     * @param id
     * @return
     */
    public static User findUserById(Integer id) throws DataAccessException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs=null;
        User user=null;
        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .append(" where id=? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1,id);
            rs=ps.executeQuery();
            while(rs.next()){
               user=new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
            }
        } catch (DataAccessException e) {
            throw e;
        } catch (SQLException e) {
            throw new DataAccessException("数据库访问失败");
        } finally {
            JDBCUtil.close(conn,ps,rs);
        }
        return user;
    }


}
